<script setup lang="ts">
import { ref, onBeforeMount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useFavoriteStore } from '@renderer/stores/favorite'
import ContextMenu from '@renderer/components/ContextMenu.vue'
import CatImage from '@renderer/components/CatImage.vue'
import { storageLocal } from '@renderer/tools/index'

import type { OwnplayInfo } from '@renderer/stores/favorite'

const { ownplay, favoriteTrack } = storeToRefs(useFavoriteStore())
const { removePlaylist, getFavorite } = useFavoriteStore()
const router = useRouter()
const contextMenuRef = ref<InstanceType<typeof ContextMenu>>()
const favorite = computed(() => favoriteTrack.value.info)

onBeforeMount(() => {
  getFavorite()
})

function doPlaylist(data: OwnplayInfo) {
  storageLocal().setItem('track-album', data)
  router.push({ name: 'track-album' })
}

function doFavorite() {
  storageLocal().setItem('track-album', favoriteTrack.value)
  router.push({ name: 'track-album' })
}
</script>

<template>
  <ContextMenu ref="contextMenuRef" v-slot="{ data }: { data: OwnplayInfo }">
    <div class="item" @click="removePlaylist(data.id)">删除歌单</div>
  </ContextMenu>
  <div class="library-page">
    <div class="cover-row">
      <div class="item" @click="doFavorite">
        <CatImage :src="favorite.cover" :width="200" :height="200" />
        <div class="text">
          <div class="title">我喜欢的音乐</div>
          <div class="info">{{ favorite.songcount }} 首歌 · by {{ favorite.author }}</div>
        </div>
      </div>
      <div
        v-for="f in ownplay"
        :key="f.id"
        class="item"
        @click="doPlaylist(f)"
        @contextmenu.prevent="(e) => contextMenuRef?.open(e, f)"
      >
        <CatImage :src="f.info.cover" :width="200" :height="200" />
        <div class="text">
          <div class="title">{{ f.info.title }}</div>
          <div class="info">{{ f.info.songcount }} 首歌 · by {{ f.info.author }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less">
.library-page {
  .cover-row {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 44px 24px;
    .item {
      color: var(--color-text);
      img {
        width: 100%;
        border-radius: 0.75em;
        border: 1px solid rgba(0, 0, 0, 0.04);
      }
      .text {
        margin-top: 8px;
        .title,
        .info {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          line-clamp: 2;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        .title {
          font-weight: 600;
          line-height: 20px;
          word-break: break-all;
        }
        .info {
          font-size: 12px;
          opacity: 0.68;
          line-height: 18px;
          word-break: break-word;
        }
      }
    }
  }
}
</style>
